package com.Policing.Fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Ip_set.Ip_Set;
import com.Policing.Okhttps.HttpOkHttp;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.Since_case.Since_case;
import com.Policing.bean.query_bean;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import java.util.HashMap;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2019/5/18.
 */

public class Query extends Fragment {
    private ImageView opmenu;
    private Button scan_img;
    private String url="http://"+ Ip_Set.IP+"/api/deviceQuery";
    private SlideSideMenuExampleActivity content;
    private EditText query_et;
    private TextView facilityNumber,facilityname,model,producers,staus,unit,site,price,date,title_text;
    //设备编号，设备名称，型号，生产厂家，状态，单位，存放位置，单价，入账日期
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.query_message, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        content = (SlideSideMenuExampleActivity) getActivity();
        inview();
        scan_img.setOnClickListener(v -> startQrCode());
        title_text.setText("设备查询");
        opmenu.setOnClickListener(v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
        query_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                query_et.selectAll();
                if (query_et.length()>2){
                    check(query_et.getText().toString().trim());
                }
            }
        });

    }

    private void inview() {
        query_et = (EditText) content.findViewById(R.id.query_et);
        title_text = (TextView) content.findViewById(R.id.title_text);
        facilityNumber = (TextView) content.findViewById(R.id.facilityNumber);
        facilityname = (TextView) content.findViewById(R.id.facilityname);
        model = (TextView) content.findViewById(R.id.model);
        opmenu = (ImageView) content.findViewById(R.id.opmenu);
        producers = (TextView) content.findViewById(R.id.producers);
        staus  = (TextView) content.findViewById(R.id.staus);
        unit = (TextView) content.findViewById(R.id.unit);
        site = (TextView) content.findViewById(R.id.site);
        price = (TextView) content.findViewById(R.id.price);
        date = (TextView) content.findViewById(R.id.date);
        scan_img = (Button) content.findViewById(R.id.query);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            check(scanResult);

        }
    }

    private void check(String scanResult) {
        Map<String,String> map = new HashMap<>();
        map.put("deviceNumber",scanResult);
        map.put("source", Since_case.set().getSource());
        HttpOkHttp.getInstance().requestPost(url, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(String s) {
                Log.i("querydata",s);
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<query_bean>() {}.getType();
                final query_bean jsonBean = gson.fromJson(s, type);
                content.runOnUiThread(() -> {
                    if (jsonBean.getState().equals("0")){
                        Toast.makeText(content,"服务器异常！",Toast.LENGTH_SHORT).show();
                        facilityNumber.setText("");
                        facilityname.setText("");
                        model.setText("");
                        producers.setText("");
                        staus.setText("");
                        date.setText("");
                        unit.setText("");
                        site.setText("");
                        price.setText("");
                    }else if (jsonBean.getState().equals("1")){
                                facilityNumber.setText(jsonBean.getDevice().getDeviceNumber());
                                facilityname.setText(jsonBean.getDevice().getDeviceName());
                                model.setText(jsonBean.getDevice().getModel());
                                producers.setText(jsonBean.getDevice().getFactory());
                                staus.setText(jsonBean.getDevice().getStatus());
                                date.setText(jsonBean.getDevice().getCreatedate());
                                unit.setText(jsonBean.getDevice().getUnit());
                                site.setText(jsonBean.getDevice().getPlace());
                                price.setText(jsonBean.getDevice().getAmount());

                    }else if (jsonBean.getState().equals("2")){
                        facilityNumber.setText("");
                        facilityname.setText("");
                        model.setText("");
                        producers.setText("");
                        staus.setText("");
                        date.setText("");
                        unit.setText("");
                        site.setText("");
                        price.setText("");
                        Toast.makeText(content,"查无此设备！",Toast.LENGTH_SHORT).show();

                    }
                });
            }

            @Override
            public void requestFailure(String message) {
                Log.i("querydata",message);
            }
        },String.class);
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;

        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
}
